package org.celstec.mobilegame;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.celstec.mobilegame.gamaray.Dimension;
import org.celstec.mobilegame.gameLoaders.LocatoryLoader;
import org.celstec.mobilegame.server.PMF;
import org.celstec.mobilegame.locatory.Locatory;
import org.celstec.mobilegame.locatory.LocatoryPlay;
import org.celstec.mobilegame.locatory.User;
import org.jdom.Document;

public class LocatoryServlet extends HttpServlet {

	// public static HashMap<String, Locatory> games = new HashMap<String,
	// Locatory>();

	public static HashMap<String, LocatoryPlay> hm = new HashMap<String, LocatoryPlay>();

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		doGet(req, resp);
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			if (req.getServerName().equals("127.0.0.1")
					|| req.getServerName().equals("145.20.132.160")
					|| req.getServerName().equals("localhost")) {
				Dimension.baseUrl = "http://celstec1.appspot.com/";
			} else {

				Dimension.baseUrl = "http://celstec1.appspot.com/";

			}
			// System.out.println(Dimension.url + " " + req.getServerName());
			resp.setContentType("application/gamaray-gddf;  charset=UTF-8");
			String uid = req.getParameter("uid");
			User u = User.getUser(uid);
			double lat = 0;
			double lon = 0;
			if (req.getParameter("lat") != null) {
				lat = Double.parseDouble(req.getParameter("lat"));
				lon = Double.parseDouble(req.getParameter("lon"));
			}
			String p = req.getParameter("p");

			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				String query = "select from " + LocatoryPlay.class.getName()
						+ " where name =='" + p + "'";
				List<LocatoryPlay> plays = (List<LocatoryPlay>) pm.newQuery(
						query).execute();
				LocatoryPlay play = null;
				if (plays.size() != 0) {
					play = plays.get(0);
				}
				play.initNotPersistentObjects(pm);
//				LocatoryPlay play = LocatoryPlay.getObjectByName(p);
				if (u == null) {
					User.storeUser(uid, lat, lon, play.key);
					u = User.getUser(req.getParameter("uid"));
				}
				query = "select from " + User.class.getName()
						+ " where uid =='" + uid + "'";
				List<User> user = (List<User>) pm.newQuery(query).execute();
				if (user.size() != 0) {
					u = user.get(0);
				}
				u.setLat(lat);
				u.setLon(lon);
				u.initNotPersistentObjects(pm);

				Dimension d = play.getDimension(u, req);
				resp.getWriter().write(d.generateDimensionXml());
			} finally {
				pm.close();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
